// 全局变量
var today = new Date();
var todayTxt = today.format('yyyy-MM-dd');

var MY_PRESCRIPTION_VIOLATE = (function() {

	function loadItem(){
		//清除排序
		var  oTable = document.getElementById("dataTable");
		oTable.sortCol = -1;
		//重置全部排序图标
		$("after").css("opacity",0.3);
		$("before").css("opacity",0.3);

		var params = getParams();
		if(params) {
            var $tbody = $('#tbodyViolateInstitutionList');
            $tbody.empty();

            WeKnow.loading();

            $.ajax({
                type: "POST",
                url: "invs_exchange_statistics.do/load",
                dataType: "json",
                data: params,
                async: true,//异步调用
                success: function (data) {

                    WeKnow.closeLoading();

                    if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

                    if (data.errcode == 0) {
                        var e = '';//初始化
                        // 数据列表
                        if ('violateCntList' in data && data.statisticsList.length == 0) {
                            e += '<tr class="danger">';
                            e += '<td colspan=5 class="text-left">暂无数据</td>';
                            e += '</tr>';
                        } else {
                            $(data.statisticsList).each(function (idx, _a) {
								e += '<tr class="pointer" ';
                                e += ' data-table_name="' + _a.tableName + '"';
                                e += ' data-type="' + _a.type + '"';
                                e += '>';
                                // 表名
                                e += '<td class="text-left">' + _a.tableName + '</td>';
								// 类型
								e += '<td class="text-left">';
								if(_a.type == 1){
									e += "基层诊所数据传输异常";
								}else if(_a.type == 2){
									e += "基层诊所数据更新异常";
								}else if(_a.type == 3){
									e += "公立医疗机构数据传输";
								}else{
									e += "其他。type:" + _a.type;
								}
								e += '</td>';
                                // 数据统计数
                                e += '<td class="text-right">' + _a.dataCount + '</td>';
                                //查看
								//if(_a.type == 1 || _a.type == 2){
									e += '<td class="text-center"><button class="btn btn-default btn-sm" name="showDetail">查看</button></td>';
								//}else{
									//e += '<td class="text-center"></td>';
								//}
                                e += '</tr>';
                            });
                        }
                        $tbody.append(e);

                    } else if (data.errcode == -1) {
                        WeKnow.errorMsg(data.errMsg);
                    } else {
                        WeKnow.systemMsg('查询失败，请重新登录后再试');
                    }
                }
            });
        }
	}
	

	// 收集页面查询参数
	function getParams(){
		
		var data = {};

		// 标本日期 from - to
		var $dtFrom = $('#dtFrom');
        var $dtTo = $('#dtTo');

		if ( !$dtFrom.val().length ){
			WeKnow.errorMsg('请输入查询开始日期');
			$dtFrom.focus();
			return false;
		}
		
		var dtFrom = $dtFrom.val();
		if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询开始日期格式不正确');
			$dtFrom.focus();
			return false;
		}
		data.dtFrom = dtFrom;
		
		// 查询日期to

		if ( !$dtTo.val().length ){
			WeKnow.errorMsg('请输入查询结束日期');
			$dtTo.focus();
			return false;
		}
		
		var dtTo = $dtTo.val();
		if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询结束日期格式不正确');
			$dtTo.focus();
			return false;
		}
        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
		data.dtTo = dtTo;
		
		// 类型
		var type =  $('#type').val();
		data.type = type;
		// 表名
		var tableName = $.trim( $('input[name="tableName"]').val());
		if ( tableName.length ){
			data.tableName = tableName;
		}
		return data;
	}
	
	// 收集页面查询参数
	function getDetailParams(){
		
		var data = {};
		
		// 标本日期 from - to
		var $dtFrom = $('#dtFrom');
		if ( !$dtFrom.val().length ){
			WeKnow.errorMsg('请输入查询开始日期');
			$dtFrom.focus();
			return false;
		}
		
		var dtFrom = $dtFrom.val();
		if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询开始日期格式不正确');
			$dtFrom.focus();
			return false;
		}
		data.dtFrom = dtFrom;
		
		// 查询日期to
		var $dtTo = $('#dtTo');
		if ( !$dtTo.val().length ){
			WeKnow.errorMsg('请输入查询结束日期');
			$dtTo.focus();
			return false;
		}
		
		var dtTo = $dtTo.val();
		if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询结束日期格式不正确');
			$dtTo.focus();
			return false;
		}
        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
		data.dtTo = dtTo;
		// 表名
		data.tableName = $('#dataTableName').val();
		// 类型
		data.type = parseInt($('#dataType').val());
		return data;
	}
	
	
	return {
		getDetailParams:getDetailParams,
		loadItem:loadItem
	}
})();

$(document).ready(function() {
	
	// 页面初期数据查询
	MY_PRESCRIPTION_VIOLATE.loadItem();
	
	$(".my_date_control" ).datepicker({
		changeMonth: true,
		changeYear: true,
        dateFormat: 'yy-mm-dd',//日期格式  
        yearSuffix: '年', //年的后缀
        showMonthAfterYear:true,//是否把月放在年的后面  
        maxDate: (function() {
        	return todayTxt;
        })(),//最大日期  
        yearRange: (function() {
        	// '1990:2010'
        	var year1 = '1900';
        	var year2 = today.getFullYear();
        	return year1 + ':' + year2;
        })(),
        monthNamesShort: ['01','02','03','04','05','06','07','08','09','10','11','12'],
        dayNamesMin: ['日','一','二','三','四','五','六'],
        onUpdatedDatepicker: function(_year, _month, _calendar) {
        	console.log('onUpdatedDatepicker');
        	var $c = $('div#ui-datepicker-div');
			$c.find('td[data-handler="selectDay"]').each(function(idx, d) {
				var $d = $(d);
				$d.css({'pointer-events': 'auto', 'opacity': 1});
    		});
        }
	});

	$('#registryStatus').on('change',function(){
		MY_PRESCRIPTION_VIOLATE.loadItem();
	});
	$('#search').on('click',function(){
		MY_PRESCRIPTION_VIOLATE.loadItem();
	});
	
	
	var $thead= $('thead#thead-prescription');
	var $tbody= $('tbody#tbody-prescription');// 明细
	
	$('#tbodyViolateInstitutionList').on('click','button[name="showDetail"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		var tableName = $parentTr.data('table_name');
		$('#dataTableName').val(tableName);
		var type = $parentTr.data('type');
		$('#dataType').val(type);
		var params = MY_PRESCRIPTION_VIOLATE.getDetailParams();
       if(params) {
		MY_EXCHANGE_STATISTICS_COM.loadDetailItem(params, $thead, $tbody);
    	// 子页面显示诊所名
    	$('#institution_name_dis').text(tableName + '(' + $('#dtFrom').val() + '-' + $('#dtTo').val() + ')');

    	$('.input-toggle').toggle();}
	});
	
	$('#backToWorkspace').on('click',function(){
		$('.input-toggle').toggle();
	});
	// 下拉框变化时刷新 
	$('#msgId,#checkSt').on('change',function(){
		var params = MY_PRESCRIPTION_VIOLATE.getDetailParams();
        if(params) {
            MY_PRESCRIPTION_VIOLATE_COM.loadDetailItem(params, $thead, $tbody);
        }
	});

	// 下拉框变化时刷新
	$('#prescriptionType').on('change',function(){
		MY_PRESCRIPTION_VIOLATE.loadItem();
	});
	
	// 跟进
	$tbody.on('click','button[name="follow_up"]',function(){
		
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		
		WeKnow.loading();
		
		$.ajax({ 
	        type: "POST", 
	        url: "invs_prescription_violate.do/update", 
	        data: {violateId:$parentTr.data('violate_id'),institutionId:$parentTr.data('institution_id')},
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		$parentTr.find('.follow-status').text('已跟进');
	        		$parentTr.find('button[name="follow_up"]').remove();//删除跟进按钮
	        		WeKnow.successMsg('更新成功');
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('更新失败，请重新登录后再试');
	        	}
	        }
		});
	});
	
	// 查看处方
	$tbody.on('click','button[name="showPre"]',function(){
		
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		
		WeKnow.loading();

		$.ajax({ 
	        type: "POST", 
	        url: "invs_prescription_violate.do/show_prescription", 
	        data: {violateId:$parentTr.data('violate_id'),institutionId:$parentTr.data('institution_id')},
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		MY_WEST_PRESCRIPTION.resetPrintBody(data.outpatient);
	        		var keepAttr = ["class", "style"];
	    			var options = {retainAttr: keepAttr};
	    			$('#printDiv').printArea(options);
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查看处方失败，请重新登录后再试');
	        	}
	        }
		});
	});
	
	// 显示申诉图片
	$('#tbody-prescription').on('click','button[name="showAppealAtta"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		
		var appealAtta = $parentTr.data('appeal_atta');
		var institutionId = $('#institutionId').val();
		// 显示交接单图片
		MY_SHOW_IMG.createShowImgModal(institutionId ,appealAtta);
	});
	
	// 处理申诉 OR 取消异常   注：申诉处理由于多个页面共用，故提炼成appeal.js
	$('#tbody-prescription').on('click','button[name="closeIllegal"],button[name="check"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		
		var illegalId = $parentTr.data('illegal_id');
		var originBtnName= $that.prop('name');
		// 更新用模态框
		var params = MY_PRESCRIPTION_VIOLATE.getDetailParams();
        if(params) {
            MY_APPEAL.createModalWin
            (illegalId, originBtnName,
                function () {
                    MY_PRESCRIPTION_VIOLATE_COM.loadDetailItem(params, $thead, $tbody);
                }
            );
        }
	});
	
	// 导出
	$('a#export').on('click',function(){
		
		var $that = $(this);
	
		var data = {};
		data.startDt = new Date().format("yyyy-MM-dd");
		data.endDt = data.startDt;
		
    	var url = WeKnow.getRealPath() + '/invs_prescription_violate.do/output';
    	
    	WeKnow.loading();
    	$.fileDownload(url,
    		{
            httpMethod: 'POST',
            data: data,
            prepareCallback:function(url){
            	console.log('download start')
            	WeKnow.loading();
            },
            successCallback:function(url){
            	console.log('download end')
            	WeKnow.closeLoading();
            },
            failCallback: function (html, url) {
            	WeKnow.errorMsg('下载失败');
            }
         });
	});


});